const getRawBody = require("raw-body")
const {parseXml} = require("./utils");
const {templates} = require("./templates")
exports.HandlePostMsg = async (req, res, next) => {
    const xml = await getRawBody(req, {
        length: req.headers['content-length'],
        limit: '1mb',
        encoding: 'utf-8'
    })
    try {
        const formatResult = await parseXml(xml)
        const {
            ToUserName,
            FromUserName,
            MsgType,
            Content,
            MediaId,
            Location_X,
            Location_Y,
            Title,
            Event,
            Description,
            Url
        } = formatResult
        let replyMessage;
        if (MsgType === 'event' && Event === 'subscribe') {
            // 用户关注公众号时的回复
            replyMessage = templates.replyText(FromUserName, ToUserName, '感谢关注我们的公众号！');
        } else {
            switch (MsgType) {
                case 'text':
                    replyMessage = templates.replyText(FromUserName, ToUserName, Content);
                    break;
                case 'image':
                    replyMessage = templates.replyImage(FromUserName, ToUserName, MediaId);
                    break;
                case 'voice':
                    replyMessage = templates.replyVoice(FromUserName, ToUserName, MediaId);
                    break;
                case 'video':
                    replyMessage = templates.replyVideo(FromUserName, ToUserName, MediaId);
                    break;
                case 'location':
                    replyMessage = templates.replyLocation(FromUserName, ToUserName, Location_X, Location_Y);
                    break;
                case 'link':
                    replyMessage = templates.replyLink(FromUserName, ToUserName, Title, Description, Url);
                    break;
                default:
                    return res.send('success'); // 对于其他消息，返回 success
            }
        }
        // 只在这里发送响应一次
        if (replyMessage) {
            console.log(replyMessage)
            res.send(replyMessage);
        } else {
            res.send('success'); // 如果没有匹配到处理的消息，返回成功
        }
    } catch (e) {
        console.error('处理消息时出错:', e);
        res.status(500).send('Internal Server Error');
    }

}